package pw.goyd.game.handler.imp;

import pw.goyd.game.handler.Handler;
import pw.goyd.game.manager.RoomManager;
import pw.goyd.game.model.Room;
import pw.goyd.game.server.Log;
import pw.goyd.game.server.LoginList;
import pw.goyd.subscribe.PlayerCustomer;

public class EXITROOM extends Handler {
    /**
     * 离开房间的静态共用方法
     *
     * @param player 玩家obj
     */
    public static void process(PlayerCustomer player) {
        int roomID = player.getRoomID();
        if (roomID > -1) {
            Room tr = RoomManager.getRoom(roomID);
            if (tr == null)
                return;

            if (tr.isGame() && tr.getIsPlayingPlayer().contains(player)) {  //  强制退出
                Log.getLogger().info(player.getNickname() + " 中途退出 " + player.getRoomID());
                player.unsubRoom();             //  取消该玩家的房间订阅
                if (!tr.leaveList.contains(player))
                    tr.leaveList.add(player);
            } else {
                // 取消订阅
                RoomManager.leaveRoom(player);  //  玩家退出个人操作
                Log.getLogger().info(player.getNickname() + " 退出 roomID: " + player.getRoomID());
            }

            //房间人数小于2 没有在游戏 移出ready room
            if (tr.getPlayerCount() < 2 && !tr.isGame()) {
                RoomManager.reayRoom.remove(tr);
                tr.setReadyTime(-1);
            }
        } else {
            player.unsubRoom();             //  取消该玩家的房间订阅
        }
    }

    /**
     * 退出房间
     */
    @Override
    public void handle() {
        PlayerCustomer player = LoginList.getPlayer(ctx.getChannel().getId());

        if (player == null) {
            Log.getLogger().error("空指针--->ChannelID[" + ctx.getChannel().getId() + "]");
            return;
        }
        process(player);
    }

}
